package cn.fsd.filter.handler;

import cn.fsd.vo.Auth;
import cn.fsd.domain.User;
import cn.fsd.service.UserService;
import cn.fsd.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

@Component
@Slf4j
public class UserPassAuthHandler {

  @Autowired
  UserService userService;
  
  public Auth authenticate(ServerWebExchange exchange) {
    Auth auth= new Auth();
    MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
    String userName = params.get("username").toString();
    if (userName != null && !"".equals(userName)) {
      auth.setUserName(userName);
      String password = params.get("password").toString();
      // 先判断用户是否存在
      User user = userService.getUserByUserName(userName);
      if (user != null) {
        // 执行认证
          if (userService.checkLogin(userName, password)) {
            log.info("<===========用户:" + userName + "存在,身份验证通过!===========>");
            auth.authSuccess(Constants.LOGIN_SUCCESS);
          } else {
            auth.authFailed(Constants.PASSWORD_NOT_MATCH);
          }
      } else {
        auth.authFailed(Constants.USERNAME_NOT_EXSIT);
      }
    } else {
      auth.authFailed(Constants.USERNAME_EMPTY);
    }
    log.info("认证后得到的Authentication对象 = " + auth.toString());
    return auth;
  }
}
